use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TodoItem {
    pub id: String,
    pub owner_key: String,
    pub title: String,
    pub description: Option<String>,
    pub finished: bool,
    pub created_at: String,
    pub updated_at: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct NewTodoItem {
    pub title: String,
    pub description: Option<String>,
    pub owner_key: String,
}
pub struct TodoInputItem {
    pub title: String,
    pub description: Option<String>,
}
impl From<&String> for TodoInputItem {
    fn from(val: &String) -> Self {
        let items: Vec<String> = val
            .splitn(2, '\n')
            .collect::<Vec<&str>>()
            .iter()
            .map(|item| item.to_string())
            .collect();
        let title = items.get(0).cloned().unwrap_or_default();
        let desc = items.get(1).cloned();
        Self {
            title,
            description: desc,
        }
    }
}

impl From<TodoItem> for TodoInputItem {
    fn from(val: TodoItem) -> Self {
        Self {
            title: val.title,
            description: val.description,
        }
    }
}

impl From<TodoInputItem> for String {
    fn from(val: TodoInputItem) -> Self {
        format!("{}\n{}", &val.title, &val.description.unwrap_or_default())
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct UpdateTodoItem {
    pub id: String,
    pub owner_key: String,
    pub title: String,
    pub description: Option<String>,
    pub finished: bool,
}

impl From<TodoItem> for UpdateTodoItem {
    fn from(val: TodoItem) -> Self {
        Self {
            id: val.id.clone(),
            owner_key: val.owner_key.clone(),
            title: val.title.clone(),
            description: val.description.clone(),
            finished: val.finished,
        }
    }
}
